﻿using System;
using System.IO;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Text;

using CE.User;
using CE.Global;
using CE.Database;
using CE.Provider;
using CE.CarInsurance;
using CE.Company;
using CE.Mail;
using CE.InputOut;

public partial class car_result : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!Page.IsPostBack)
        {

            if (Session[General.CarId] != null && Session[General.UserId] != null)
            {

                //Session["CarID"] = "3271";
                //Session["UserID"] = "143";
                //Session["UserEmail"] = "cherylmae.lanot@teledirect.com.sg";
                //Session["UserName"] = "che";
                //Session[General.CarPolicyId] = "2500";

                if (Session[General.UserId] != null)
                {
                    Cache.Remove("CarResult" + Session[General.UserId].ToString() + Session[General.CarId].ToString());
                }
                else
                {
                    Cache.Remove("CarResult" + Session[General.CarId].ToString());
                }

                txtVehicleNo.Attributes.Add("onblur", "ShowValidationEffectTwo('" + txtVehicleNo.ClientID + "','" + rfvVehicleNo.ClientID + "','" + rfvVehicleNoSave.ClientID + "');DefaultVehicleNo(this, event);");
                txtVehicleNo.Attributes.Add("onfocus", "ClearText(this, event);");

                GetCarMakeModel();
                CalculatePremium();
                ResultsQuotesDataBind();

            }
            else
            {
                Response.Redirect("car-quote.aspx");
            }


        }
    }

    protected void dlCarResults_ItemDataBound(object sender, DataListItemEventArgs e)
    {
        if (e.Item.ItemType == ListItemType.Item ||
             e.Item.ItemType == ListItemType.AlternatingItem)
        {
            ImageButton imgEmailQuote = (ImageButton)e.Item.FindControl("imgEmailQuote");
            imgEmailQuote.Attributes.Add("onclick", "return confirm('Are you sure you want to send this quote?');");

            Label lblPremiumAmount = (Label)e.Item.FindControl("lblPremiumAmount");
            Label lblPromotionPrice = (Label)e.Item.FindControl("lblPromotionPrice");

            Label lblProviderCompanyName = (Label)e.Item.FindControl("lblProviderCompanyName");

            Label lblPlanName = (Label)e.Item.FindControl("lblPlanName");
            Label lblProviderCompanyID = (Label)e.Item.FindControl("lblProviderCompanyID");
            Label lblCarResultID = (Label)e.Item.FindControl("lblCarResultID");
            Image imgProviderCompanyLogo = (Image)e.Item.FindControl("imgProviderCompanyLogo");

            string _premiumAmount = DataBinder.Eval(e.Item.DataItem, "AnnualPremium").ToString().Trim();
            lblPremiumAmount.Text = "S$ " + Convert.ToSingle(_premiumAmount).ToString("#,000.00");

            lblProviderCompanyID.Text = DataBinder.Eval(e.Item.DataItem, "ProviderCompanyId").ToString();
            lblProviderCompanyName.Text = DataBinder.Eval(e.Item.DataItem, "InsurerName").ToString();
            lblPlanName.Text = DataBinder.Eval(e.Item.DataItem, "PlanName").ToString();
            lblCarResultID.Text = DataBinder.Eval(e.Item.DataItem, "CITempResultID").ToString();

            HyperLink hlnkView = (HyperLink)e.Item.FindControl("hlnkView");
            hlnkView.NavigateUrl = "car-result-detail.aspx?crid=" + lblCarResultID.Text;

            HyperLink hlnkViewTop = (HyperLink)e.Item.FindControl("hlnkViewTop");
            hlnkViewTop.NavigateUrl = "car-result-detail.aspx?crid=" + lblCarResultID.Text;

            string companylogourl = DataBinder.Eval(e.Item.DataItem, "CompanyLogoUrl").ToString();

            if (DataBinder.Eval(e.Item.DataItem, "CompanyLogoUrl").ToString().Substring(0, 1) == "~")
            {
                companylogourl = DataBinder.Eval(e.Item.DataItem, "CompanyLogoUrl").ToString().Remove(0, 1);
            }

            imgProviderCompanyLogo.ImageUrl = "http://www.comparexpress.com" + companylogourl;
        }
    }

    protected void dlCarResults_ItemCommand(object source, DataListCommandEventArgs e)
    {
        Label lblCarResultID = (Label)e.Item.FindControl("lblCarResultID");

        if (e.CommandName == "Email")
        {
            this.EmailQuote(lblCarResultID.Text);
        }

        if (e.CommandName == "ViewDetails")
        {
            if (lblCarResultID.Text.Trim() != "")
            {
                //Session["CarSelected"] = lblCarResultID.Text;
                Response.Redirect("car-result-detail.aspx?crid=" + lblCarResultID.Text);
            }
        }

        if (e.CommandName == "CallMe")
        {
            txtFlag.Text = lblCarResultID.Text;
            pnlOffline.Visible = true;
            dlCarResults.Visible = false;

        }

    }

    private void GetCarMakeModel()
    {
        string _makemodel = "";
        string _caryear = "";
        Int64 _cecarid = 0;

        if (Session[General.CarPolicyId] != null && Session[General.CarId] != null)
        {
            _cecarid = Convert.ToInt64(Session[General.CarId]);
            Int64 _cepolicyid = Convert.ToInt64(Session[General.CarPolicyId]);
            Int64 _userId = 0;

            if (Session[General.UserId] != null)
            {
                _userId = Convert.ToInt64(Session[General.UserId].ToString());
            }


            CarDetail _cardetail = new CarDetail();
            CarDetailDB _cardetaildb = new CarDetailDB();
            _cardetail = _cardetaildb.GetCar(_cecarid, _userId);

            CarPolicy _carpolicy = new CarPolicy();
            CarPolicyDB _carpolicydb = new CarPolicyDB();
            _carpolicy = _carpolicydb.GetCarPolicy(_cecarid, _cepolicyid, _userId);

            if (_cardetail != null)
            {
                _makemodel = _cardetail.MakeModelDesc; //.CarModelName + " " + _cardetail.Body + " " + _cardetail.CC + "cc " + _cardetail.Door.ToString() + " doors";
                _caryear = _cardetail.ManufactYear.ToString();
            }

            txtCarMakeModel.Text = _caryear + " - " + _makemodel;

        }

    }

    private Int32 CalculatePremium()
    {
        ClearCarInsuranceTempResult();

        MyDatabase _db = new MyDatabase();

        SortedList _sPara = new SortedList();
        _sPara.Add("@CECarId", Session[General.CarId].ToString());
        _sPara.Add("@RefCEUserId", Session[General.UserId].ToString());

        Int32 _result = 0;

        if (Convert.ToInt32(Session[CE.Global.General.UserTypeId]) ==
                Convert.ToInt32(CE.Global.CEUserType.Provider) && Session[CE.Global.General.ProviderCompanyId] != null)
        {
            if (Session[CE.Global.General.ProviderCompanyId].ToString() == CE.Configuration.MyConfigurationManager.GetAppSettingValue("LibertyProviderCompanyId"))
                _result = _db.ExecuteNonSqlSP("[sprocProviderCarInsuranceCalculationLiberty]", _sPara);
            else if (Session[CE.Global.General.ProviderCompanyId].ToString() == CE.Configuration.MyConfigurationManager.GetAppSettingValue("EtiqaProviderCompanyId"))
                _result = _db.ExecuteNonSqlSP("[sprocProviderCarInsuranceCalculationEtiqa]", _sPara);
            else if (Session[CE.Global.General.ProviderCompanyId].ToString() == CE.Configuration.MyConfigurationManager.GetAppSettingValue("HSBCProviderCompanyId"))
                _result = _db.ExecuteNonSqlSP("[sprocProviderCarInsuranceCalculationHsbc]", _sPara);
            //else if (Session[CE.Global.General.ProviderCompanyId].ToString() == CE.Configuration.MyConfigurationManager.GetAppSettingValue("RSAProviderCompanyId"))
            //    _result = _db.ExecuteNonSqlSP("[sprocProviderCarInsuranceCalculationRSA]", _sPara);
        }
        else if (Session[CE.Global.General.AgentId] != null &&
                 Session[CE.Global.General.ProviderCompanyId] != null)
        {
            if (Session[CE.Global.General.ProviderCompanyId].ToString() == CE.Configuration.MyConfigurationManager.GetAppSettingValue("LibertyProviderCompanyId"))
                _result = _db.ExecuteNonSqlSP("[sprocProviderCarInsuranceCalculationLiberty]", _sPara);
            else if (Session[CE.Global.General.ProviderCompanyId].ToString() == CE.Configuration.MyConfigurationManager.GetAppSettingValue("EtiqaProviderCompanyId"))
                _result = _db.ExecuteNonSqlSP("[sprocProviderCarInsuranceCalculationEtiqa]", _sPara);
            else if (Session[CE.Global.General.ProviderCompanyId].ToString() == CE.Configuration.MyConfigurationManager.GetAppSettingValue("HSBCProviderCompanyId"))
                _result = _db.ExecuteNonSqlSP("[sprocProviderCarInsuranceCalculationHsbc]", _sPara);
            //else if (Session[CE.Global.General.ProviderCompanyId].ToString() == CE.Configuration.MyConfigurationManager.GetAppSettingValue("RSAProviderCompanyId"))
            //    _result = _db.ExecuteNonSqlSP("[sprocProviderCarInsuranceCalculationRSA]", _sPara);
        }
        else
        {
            _result = _db.ExecuteNonSqlSP("[sprocProviderCarInsuranceCalculation]", _sPara);
        }
        return _result;
    }

    private void ResultsQuotesDataBind()
    {
        GetTempResultTableTwo(false);

        /* if (lblOfflineRequestStatus.Text == "0")
        {
            GetTempResultTableTwo(false);

            DataView dv = new DataView((DataTable)Cache["CarResult" + Session[General.UserId].ToString() + Session[General.CarId].ToString()]);
            string _strSort = "";
            if (ViewState["SortOrder"].ToString() == SortDirection.Ascending.ToString())
            {
                _strSort = " ASC";
            }
            else
            {
                _strSort = " DESC";
            }
            dv.Sort = ViewState["SortExpression"].ToString() + _strSort;
            gvCarResult.DataSource = dv;
            gvCarResult.DataBind();
        }
        else
        {
            GetTempResultTableTwo(true);
        }
         * */

        dlCarResults.DataSource = (DataTable)Cache["CarResult" + Session[General.UserId].ToString() + Session[General.CarId].ToString()];
        dlCarResults.DataBind();


        if (dlCarResults.Items.Count == 0)
            pnlOffline.Visible = true;
        else
            pnlOffline.Visible = false;

    }

    private void GetTempResultTableTwo(bool IsOfflineRequest)
    {
        MyDatabase _db = new MyDatabase();
        DataTable _dtResult = new DataTable();
        string _spName = "[sprocCarInsuranceResultSelectItemList]";
        SortedList _sPara = new SortedList();
        _sPara.Add("@CECarId", Session[General.CarId].ToString());
        _sPara.Add("@RefCEUserId", Session[General.UserId].ToString());
        _dtResult = _db.GetDataTableBySP(_spName, _sPara);
        //Response.Write(_dtResult.ToString());

        //divOfflineBanner.Visible = false;

        if (_dtResult.Rows.Count == 1)
        {
            if (_dtResult.Rows[0]["ProviderCompanyId"].ToString() != "38")
                Cache["CarResult" + Session[General.UserId].ToString() + Session[General.CarId].ToString()] = _dtResult;
            //lblResultStatus.Text = "1";
        }
        else
        {
            Cache["CarResult" + Session[General.UserId].ToString() + Session[General.CarId].ToString()] = _dtResult;
        }

        /*
        if (_dtResult.Rows.Count > 0 && IsOfflineRequest == false)
        {
            SendCarInsuranceQuote();
            imgInstantBuy.Visible = true;
            imgInstantBuy.ImageUrl = "~/images/bg/heading_buydirect.png";
            gvCarResult.Visible = true;
            divHeadingbuydirect.Visible = false; //Sakthi
            divUserRefDetail.Visible = false; //Sakthi
            lblResultStatus.Text = "1";
            divOfflineBanner.Visible = true;
        }
        else
        {
            gvCarResult.Visible = false;
            divOfflineBanner.Visible = false;
            bool isSubmitted = GetReferenceUser(Convert.ToInt64(Session[CE.Global.General.UserId].ToString()), Convert.ToInt64(Session[CE.Global.General.CarId].ToString()), "CI");
            divHeadingbuydirect.Visible = false;
            divUserRefDetail.Visible = true;

            GetDriverDOB();

            if (isSubmitted)
            {
                divNoMatchFound.Visible = false;
                divNoInstantMatchFound.Visible = true;
            }
            else
            {
                if (IsOfflineRequest)
                {
                    divNoMatchFound.Visible = false;
                    divNoInstantMatchFound.Visible = true;
                }
                else
                {
                    if (CheckMailSendCount())
                    {
                        if (CheckOfflineCommencementDate())
                        {
                            divNoMatchFound.Visible = false;
                            divNoInstantMatchFound.Visible = true;
                        }
                        else
                        {

                            divNoMatchFound.Visible = true;
                            divNoInstantMatchFound.Visible = false;

                            //divUserRefDetail.Visible = false;
                            //btnBack.Visible = true;
                            //divMessage.Visible = true;
                            //lblMessage.Visible = true;


                            //lblMessage.Text = "Sorry, we cannot get an offline quote since your commencement date is less than 5 days from now. <br/> (" + lblCommencementdate.Text + ")";

                            //if (Request.UrlReferrer.AbsolutePath.ToString().ToLower() == "/user/viewresulthistory.aspx")
                            //{
                            //    btnBack.Visible = false;
                            //}
                        }
                    }
                    else
                    {
                        divNoMatchFound.Visible = true;
                        divNoInstantMatchFound.Visible = false;
                    }
                }
            }
          
            imgInstantBuy.Visible = false;
            imgInstantBuy.ImageUrl = "~/images/bg/heading_buydirect_noresult.png";

        }
        Cache["CarResult" + Session[General.UserId].ToString() + Session[General.CarId].ToString()] = _dtResult;
        SendMailToUser();
        */
    }

    private void ClearCarInsuranceTempResult()
    {
        MyDatabase _db = new MyDatabase();

        SortedList _sPara = new SortedList();
        _sPara.Add("@CECarId", Session[General.CarId].ToString());
        _sPara.Add("@RefCEUserId", Session[General.UserId].ToString());

        _db.ExecuteNonSqlSP("[sprocProviderCarInsuranceClear]", _sPara);
    }

    private void EmailQuote(string carresultid)
    {
        string qs_carselected = carresultid;
        string _makemodel = "";
        string _garagetype = "";
        string _caryear = "";
        string _ncb = "";
        string _policystartdate = "";

        Int64 _cecarid = 0;

        if (Session[General.CarPolicyId] != null && Session[General.CarId] != null)
        {
            _cecarid = Convert.ToInt64(Session[General.CarId]);
            Int64 _cepolicyid = Convert.ToInt64(Session[General.CarPolicyId]);
            Int64 _userId = 0;

            if (Session[General.UserId] != null)
            {
                _userId = Convert.ToInt64(Session[General.UserId].ToString());
            }


            CarDetail _cardetail = new CarDetail();
            CarDetailDB _cardetaildb = new CarDetailDB();
            _cardetail = _cardetaildb.GetCar(_cecarid, _userId);

            CarPolicy _carpolicy = new CarPolicy();
            CarPolicyDB _carpolicydb = new CarPolicyDB();
            _carpolicy = _carpolicydb.GetCarPolicy(_cecarid, _cepolicyid, _userId);

            if (_cardetail != null)
            {
                _makemodel = _cardetail.MakeModelDesc; //.CarModelName + " " + _cardetail.Body + " " + _cardetail.CC + "cc " + _cardetail.Door.ToString() + " doors";
                _caryear = _cardetail.ManufactYear.ToString();
            }

            if (_carpolicy != null)
            {

                _ncb = _carpolicy.NCDPercent.ToString();

                if (_ncb == "-1")
                    _ncb = "0";

                _policystartdate = _carpolicy.CoverageCommenceDate.ToString("dd/MMM/yyyy");
            }
        }

        string _refno = "";
        string _companyName = "";
        string _insurerimageurl = "";
        string _package = "";
        string _annualprice = "";
        string _excess = "";

        string _workshoplan = "";
        string _PAinsured = "";
        bool _isPAinsuredShowImage = false;
        string _PApassenger = "";
        bool _isPApassengerShowImage = false;
        string _medicalexp = "";
        string _lossPE = "";
        bool _islossPEShowImage = false;
        string _lossuse = "";
        bool _islossuseShowImage = false;

        if (qs_carselected != "" && Session[General.UserId] != null && Session[General.CarId] != null && Session[General.UserName] != null)
        {
            if (Cache["CarResult" + Session[General.UserId].ToString() + Session[General.CarId].ToString()] != null)
            {
                DataView dv = new DataView((DataTable)Cache["CarResult" + Session[General.UserId].ToString() + Session[General.CarId].ToString()]);

                string CITempResultId = qs_carselected; // Session["CarSelected"].ToString();

                //dv.RowFilter = " CITempResultId in (" + CITempResultId.Remove(CITempResultId.Length - 1, 1) + ")";
                dv.RowFilter = " CITempResultId in (" + CITempResultId + ")";
                DataTable dtFiltered = dv.ToTable();
                if (Cache["CarResult" + Session[General.UserId].ToString() + Session[General.CarId].ToString()] != null)
                {
                    if (dtFiltered.Rows.Count > 0)
                    {
                        int rowCount = dtFiltered.Rows.Count;

                        for (int iRows = 0; iRows < rowCount; iRows++)
                        {
                            //string convertno = General.GetRefNumber(_cecarid);

                            string _providercompanyid = dtFiltered.Rows[iRows]["ProviderCompanyId"].ToString();
                            _refno = General.GetRefNumber(_cecarid);

                            if (_providercompanyid == "29")
                                _refno = "L" + General.GetRefNumber(_cecarid);
                            else if (_providercompanyid == "38")
                                _refno = "D" + General.GetRefNumber(_cecarid);

                            _companyName = dtFiltered.Rows[iRows]["insurername"].ToString();

                            _insurerimageurl = dtFiltered.Rows[iRows]["CompanyLogoUrl"].ToString();

                            if (dtFiltered.Rows[iRows]["CompanyLogoUrl"].ToString().Substring(0, 1) == "~")
                            {
                                _insurerimageurl = dtFiltered.Rows[iRows]["CompanyLogoUrl"].ToString().Remove(0, 1);
                            }

                            _package = "<strong>" + dtFiltered.Rows[iRows]["providercovertypedesc"].ToString() + "</strong>";


                            _annualprice = _annualprice + "<div style='color:#F00;font-size:20px;font-weight:bold;' >";
                            _annualprice = _annualprice + String.Format("{0:0,0.00}", Convert.ToSingle(dtFiltered.Rows[iRows]["annualpremium"].ToString())); //"999.00";
                            _annualprice = _annualprice + "</div>";

                            _excess = String.Format("{0:0,0}", Convert.ToSingle(dtFiltered.Rows[iRows]["Excess"].ToString()));
                            _workshoplan = dtFiltered.Rows[iRows]["PlanName"].ToString();

                            if (Convert.ToInt32(dtFiltered.Rows[iRows]["PolicyHolder"].ToString()) == 0)
                                _isPAinsuredShowImage = true;
                            else
                                _PAinsured = String.Format("{0:#,0}", Convert.ToInt32(dtFiltered.Rows[iRows]["PolicyHolder"].ToString()));


                            if (Convert.ToSingle(dtFiltered.Rows[iRows]["PassengerEach"].ToString()) == 0)
                                _isPApassengerShowImage = true;
                            else
                                _PApassenger = String.Format("{0:#,0}", Convert.ToSingle(dtFiltered.Rows[iRows]["PassengerEach"].ToString()));

                            _medicalexp = String.Format("{0:#,0}", Convert.ToSingle(dtFiltered.Rows[iRows]["MedicalExpense"].ToString()));

                            if (Convert.ToInt32(dtFiltered.Rows[iRows]["PersonnalEffectsLoss"].ToString()) == 0)
                                _islossPEShowImage = true;
                            else
                                _lossPE = String.Format("{0:#,0}", Convert.ToSingle(dtFiltered.Rows[iRows]["PersonnalEffectsLoss"].ToString()));


                            bool _IsCarReplace = false;

                            if (dtFiltered.Rows[iRows]["IsCarReplacement"].ToString() != "")
                                _IsCarReplace = Convert.ToBoolean(dtFiltered.Rows[iRows]["IsCarReplacement"].ToString());

                            string _strCarReplace = Convert.ToString(dtFiltered.Rows[iRows]["CarReplacement"].ToString());

                            int _IsTranspoAllowance = 0;

                            if (Convert.ToBoolean(dtFiltered.Rows[iRows]["isCashAllowance"].ToString()))
                                _IsTranspoAllowance = 1;

                            string _strTranspoAllowance = Convert.ToString(dtFiltered.Rows[iRows]["CashAllowance"].ToString());
                            string _strMaxTranspoAllowanceDays = Convert.ToString(dtFiltered.Rows[iRows]["MaxCashAllowanceDays"].ToString());

                            if (_IsCarReplace)
                            {
                                _lossuse = "Courtesy Car <br/>" + "max " + _strCarReplace + " day(s)";
                            }
                            else
                            {
                                if (_IsTranspoAllowance == 0)
                                {
                                    _lossuse = "Transport Allowance<br/> S$" + _strTranspoAllowance + "/day <br/> max " + _strMaxTranspoAllowanceDays + " day(s)";
                                }
                                else
                                {
                                    _islossuseShowImage = true;
                                    //imgLossUse.Visible = true;
                                    //imgLossUse.ImageUrl = dtFiltered.Rows[iRows]["CarReplacementUrl"].ToString();

                                }
                            }
                        }
                    }
                }
            }
        }

        string _emailList = "", _title = "";
        System.Text.StringBuilder _message = new System.Text.StringBuilder();
        _emailList = Session[CE.Global.General.UserEmail].ToString();
        //_emailList += ";team@comparexpress.com";
        //string _currentDomainUrl = "http://" + HttpContext.Current.Request.Url.Host.ToString() + "/";
        string _currentDomainUrl = "http://www.comparexpress.com/";
        _title = "";

        #region set authSalt and uid
        AccountDB _accountdb = new AccountDB();
        Account _account = _accountdb.GetUserAccount(Session[CE.Global.General.UserEmail].ToString(), Convert.ToInt32(CE.Global.CEUserType.Customer));
        string confirmUrl = "";
        if (_account != null)
        {
            string salt = CE.Security.MySecurity.Encrypt("redirect" , true);
            string strGUID = _accountdb.GetGUID(_account.CEID);
            salt = salt.Replace("+", "");
            _account.AuthSalt = salt;
            if (_accountdb.Insert(_account) > 0)
            {
                confirmUrl = _currentDomainUrl;
                confirmUrl += "user/email-redirect.aspx";
                confirmUrl += "?authkey=" + salt + "&uid=" + strGUID;
            }
        }
        #endregion 

        _title = "CompareXpress.com (Ref No : " + _refno + ")";

        _message.Append("<table cellpadding='0' cellspacing='0' border='0' width='270' style='font-family:Arial, Helvetica, sans-serif; font-size:12px; margin:0 auto;'>");
        _message.Append("<tr><td style='border-bottom:1px solid #ccc;' align='center'><img src='http://www.comparexpress.com/images/nav/logo_comparexpress.png' alt='' height='78' /><br/><br/>");
        _message.Append("Thank you for choosing CompareXpress.com <br/><strong>Here is your Quote Details </strong><br />");
        _message.Append("<a href='" + confirmUrl + "' target='_blank'>View Saved Quotes</a> <br />");
        _message.Append("<br/></td></tr>");

        _message.Append("<tr><td style='border-bottom:1px solid #ccc;'><br /><table cellspacing='0' cellpadding='2' width='100%' border='0'>");

        _message.Append("<tr><td valign='top'>Quote Ref Number</td>");
        _message.Append("<td valign='top'><strong><u>" + _refno + "</u></strong></td></tr>");

        _message.Append("<tr><td valign='top'>Car Make & Model</td>");
        _message.Append("<td valign='top'><strong>" + _makemodel + "</strong></td></tr>");

        _message.Append("<tr><td valign='top'>Car Model Year</td>");
        _message.Append("<td valign='top'><strong>" + _caryear + "</strong></td></tr>");

        _message.Append("<tr><td valign='top'>Cover Commencement Date</td>");
        _message.Append("<td valign='top'><strong>" + _policystartdate + "</strong></td></tr>");

        _message.Append("<tr><td valign='top'>NCD</td>");
        _message.Append("<td valign='top'><strong>" + _ncb + "%</strong></td></tr>");

        _message.Append("<tr><td valign='top'>Quote Date</td>");
        _message.Append("<td valign='top'><strong>" + CE.Global.General.GetUTCDateTime().ToString("dd/MMM/yyyy") + "</strong></td></tr>");

        _message.Append("</table><br /></td></tr><tr><td width='360'><br />");

        _message.Append("<table width='100%' border='0' cellpadding='5' cellspacing='0'  class='table_details'>");

        _message.Append("<tr><td width='45%'></td>");
        _message.Append("<td width='55%' align='center' style='background:#e0e0e0; border-bottom:white 1px dashed;'>");
        _message.Append("<img src='" + _currentDomainUrl + _insurerimageurl + "' width='120px' /></td></tr>");

        _message.Append("<tr><td><strong>Insurer</strong></td>");
        _message.Append("<td align='center' style='background:#d5d5d5; color:black;' ><strong>" + _companyName + "</strong></td></tr>");

        _message.Append("<tr><td></td>");
        _message.Append("<td align='center' style='background:#d5d5d5;'>" + _package + "</td></tr>");

        _message.Append("<tr><td align='left' style='background:#d5d5d5' ><strong>Premium</strong></td>");
        _message.Append("<td align='center' style='background:#d5d5d5; color:black; font-size:16px;'><strong>" + _annualprice + "</strong></td></tr>");

        _message.Append("<tr><td style='border-bottom:1px solid #ccc;'><strong>Excess</strong></td>");
        _message.Append("<td align='center' style='background:#d5d5d5' >" + _excess + "</td></tr>");

        _message.Append("<tr><td style='border-bottom:1px solid #ccc;'><strong>Workshop Plan</strong></td>");
        _message.Append("<td align='center' style='background:#d5d5d5' >" + _workshoplan + "</td></tr>");

        _message.Append("<tr><td style='border-bottom:1px solid #ccc;'><strong>Personal Accident (insured)</strong></td>");
        _message.Append("<td align='center' style='background:#c5c5c5;'>");

        if (_isPAinsuredShowImage)
            _message.Append("<img src='http://www.comparexpress.com/images/icon/X.png' /></td></tr>");
        else
            _message.Append(_PAinsured + "</td></tr>");

        _message.Append("<tr><td style='border-bottom:1px solid #ccc;'><strong>Personal Accident (each passenger)</strong></td>");
        _message.Append("<td align='center' style='background:#d5d5d5' >");

        if (_isPApassengerShowImage)
            _message.Append("<img src='http://www.comparexpress.com/images/icon/X.png' /></td></tr>");
        else
            _message.Append(_PApassenger + "</td></tr>");

        _message.Append("<tr><td style='border-bottom:1px solid #ccc;'><strong>Medical Expense</strong></td>");
        _message.Append("<td align='center' style='background:#d5d5d5' >" + _medicalexp + "</td></tr>");

        _message.Append("<tr><td style='border-bottom:1px solid #ccc;'><strong>Loss of Personal Effects</strong></td>");
        _message.Append("<td align='center' style='background:#d5d5d5' >");

        if (_islossPEShowImage)
            _message.Append("<img src='http://www.comparexpress.com/images/icon/X.png' /></td></tr>");
        else
            _message.Append(_lossPE + "</td></tr>");

        _message.Append("<tr><td style='border-bottom:1px solid #ccc;'><strong>Loss of Use (benefit)</strong></td>");
        _message.Append("<td align='center' style='background:#d5d5d5' >");

        if (_islossuseShowImage)
            _message.Append("<img src='http://www.comparexpress.com/images/icon/X.png' /></td></tr>");
        else
            _message.Append(_lossuse + "</td></tr>");

        _message.Append("</table><br /><br />");
        //_message.Append("<a href='tel:022688222'><img src='http://www.gluaygluay.com/images/banners/hotline_en.png' alt='Call Us at 02 268 8222' width='270' border='0' /></a>");
        //_message.Append("<br /><br /><br />");

        _message.Append("<strong>Remarks</strong><br />");
        _message.Append("1 - The quotation valid for 7 days and subject to change without notice according to policy of company.<br />");
        _message.Append("2- Premium and coverage are subject to underwriting criteria of insurance company. <br />");
        _message.Append("<br /><a href='" + confirmUrl + "' target='_blank'>View Saved Quotes</a> <br />");
        _message.Append("</td></tr><tr><td id='email_footer'></td>");
        _message.Append("</tr></table><br /><br /><hr />This Quote is subject to the insurer's final confirmation and coverage is only effective when the insurer has accepted the risk.<br /><br />");
        _message.Append("<i>This is a computer-generated email. Please do not reply to this email.</i><hr />");

        string bccemail = CE.Configuration.MyConfigurationManager.GetAppSettingValue("Mobile.CX_CARBCC");
        MyMailManager.SendCRMMessage(_emailList, "", bccemail, _title, _message.ToString());

        Response.Redirect("email-confirm.aspx?type=email&resultid=" + carresultid);
    }

    protected void btnSaveOffline_Click(object sender, EventArgs e)
    {
        txtVehicleNo.Text = General.ClearScriptTag(txtVehicleNo.Text);

        if (Page.IsValid)
        {
            if (Session[General.CarId] != null && Session[General.UserId] != null)
            {
                if (txtFlag.Text != "0")
                    CallMeRequest();
                else
                {
                    CarDetailDB cardtldb = new CarDetailDB();

                    Int64 iCarid = 0;
                    Int64 iUserid = 0;

                    if (Session[General.CarId] != null)
                        iCarid = int.Parse(Session[General.CarId].ToString());

                    if (Session[General.UserId] != null)
                        iUserid = int.Parse(Session[General.UserId].ToString());


                    cardtldb.UpdateCarDetailVehicleNo(iCarid, iUserid, txtVehicleNo.Text, "mobile");

                    string _AgentEmail = "";
                    _AgentEmail = CE.Configuration.MyConfigurationManager.GetAppSettingValue("Mobile.OLAgentEmail");

                    string _message = "Customer Name: " + Session[General.UserName].ToString();
                    string _title = "Liberty Insurance Offline Quotes Request by " + Session[General.UserName].ToString() + " (mobile)";

                    _message += "<br/><br/>Car ID : " + Session[General.CarId].ToString();
                    _message += "<br/><br/>Customer Email : " + Session[General.UserEmail].ToString();
                    _message += "<br/><br/>Contact No : " + Session[General.UserPhoneNo].ToString();

                    HttpCookie _cookie = Request.Cookies.Get("CXMobile_Quote");
                    if (_cookie != null)
                    {
                        _message += "<br/><br/>Make/Model : " + txtCarMakeModel.Text; // _cookie.Values.Get("CustomerCarMake") + " " + _cookie.Values.Get("CustomerCarModel");
                        _message += "<br/><br/>Commencement Date : " + _cookie.Values.Get("CustomerCommencementDate");

                    }

                    _message += "<br/><br/>Vehicle Number : " + txtVehicleNo.Text;

                    MyMailManager.SendCXBrokerNotification(_AgentEmail, _title, _message);

                    General.ClearAllSession(this.Page, "ALL");
                    Response.Redirect("usermessage.aspx");
                }
            }
            else
            {
                Response.Redirect("car-quote.aspx");
            }
        }
    }

    private void CallMeRequest()
    {
        if (Session[CE.Global.General.UserId] != null && Session[CE.Global.General.CarId] != null)
        {
            string _message = "";
            string _title = "";
            string _ec = "";
            string _calltype = "1";
            string _makemodel = "";
            string _commencement = "";

            _message = "Customer Name: " + Session[General.UserName].ToString();
            _title = "Call Me request by " + Session[General.UserName].ToString() + " for Liberty Insurance (mobile)";
            if (IsValid)
            {
                Int64 _result = 0;
                ContactUser _contactuser = new ContactUser();
                ContactUserDB _contactuserdb = new ContactUserDB();

                _contactuser.RefCEUserId = Convert.ToInt64(Session[General.UserId].ToString());
                _contactuser.ProductId = Convert.ToInt64(Session[General.CarId].ToString());
                _contactuser.ProviderCompanyId = 29;
                _ec = "1029";
                _contactuser.InsuranceType = "CI";
                _contactuser.FullName = Session[General.UserName].ToString();
                _contactuser.ContactNo = Session[General.UserPhoneNo].ToString();
                _contactuser.CallTime = 4;
                _contactuser.AgentId = 0;
                _contactuser.Status = true;
                _contactuser.Info1 = _calltype;
                _contactuser.Info2 = txtVehicleNo.Text;
                _contactuser.Info3 = "";

                _result = _contactuserdb.Insert(_contactuser);
                if (_result > 0)
                {
                    CXAgent _cxagent = new CXAgent();
                    CXAgentDB _cxagentdb = new CXAgentDB();
                    Int64 _ProductId = 0;
                    Int64 _AgentId = 0;
                    Int64 _CEID = Convert.ToInt64(Session[General.UserId].ToString());
                    string _AgentName = "";
                    string _AgentEmail = "";
                    string _CCEmail = "";
                    string _BCCEmail = "";
                    DataTable _dtCXAgent = _cxagentdb.GetCXAgentList(_CEID, "CM", 0);
                    if (_dtCXAgent != null && _dtCXAgent.Rows.Count > 0)
                    {
                        _AgentId = Convert.ToInt64(_dtCXAgent.Rows[0]["AgentId"].ToString());
                        _AgentName = _dtCXAgent.Rows[0]["AgentName"].ToString();
                        _AgentEmail = _dtCXAgent.Rows[0]["Email"].ToString();

                        _ProductId = Convert.ToInt64(Session[General.CarId].ToString());
                        _contactuserdb.Update(_CEID, _AgentId, _contactuser.ProviderCompanyId, "CM", _ProductId);

                        HttpCookie _cookie = Request.Cookies.Get("CXMobile_Quote");
                        if (_cookie != null)
                        {
                            _makemodel = txtCarMakeModel.Text; // _cookie.Values.Get("CustomerCarMake") + " " + _cookie.Values.Get("CustomerCarModel");
                            _commencement = _cookie.Values.Get("CustomerCommencementDate"); 
                        }

                        _message += "<br/><br/>Make/Model : " + _makemodel;
                        _message += "<br/><br/>Commencement Date : " + _commencement;
                        _message += "<br/><br/><b>Insurer : <span style='color:#f00'> Liberty Insurance";
                        _message += "</span></b><br/><br/>Contact No : " + Session[General.UserPhoneNo].ToString(); ;
                        _message += "<br/><br/>Call Time : Anytime ";
                        _message += "<br/><br/>Agent Name : " + _AgentName;
                        //string _emailList = ConfigurationManager.AppSettings["CICallMeMessageReceiver"].ToString();
                        //MyMailManager.SendCRMMessage(_emailList, _title, _message);
                        _CCEmail = ConfigurationManager.AppSettings["Mobile.CC_CICallMeMessageReceiver"].ToString();
                        _BCCEmail = ConfigurationManager.AppSettings["Mobile.BCC_CICallMeMessageReceiver"].ToString();
                        MyMailManager.SendCallMeMessage(_AgentEmail, _CCEmail, _BCCEmail, _title, _message);
                        Response.Redirect("usermessage.aspx");
                    }
                }
            }
        }
    }

}
